import Layouts from '@/components/Layout';
import { addActivity, addTour, getActivityList, getTourList } from '@/service/api/touractivity';
import { ActivityList, TourForm, TourList } from '@/types/touractivity';
import {
  Button,
  Card,
  Cascader,
  Empty,
  Form,
  Input,
  InputNumber,
  Radio,
  Select,
  Slider,
  Space,
  Tabs,
} from 'antd';
import React, { useEffect, useState } from 'react';
import configs from '../../../config/env';
import { history, useLocation } from 'umi';
import './index.less';
import PicUpload from '@/components/PicUpload';
import { CitiesList, CountriesList } from '@/types/loaction';
import { getCityByCountry, getCountriesList } from '@/service/api/location';
import { CommonData } from '@/types/common';
import { getType } from '@/service/api/common';
const { SHOW_CHILD } = Cascader;
interface Options {
  value: string;
  label: string;
}
interface TourFormExtend extends TourForm {
  people?: number[];
}
interface OptionTags extends Options {
  children?: OptionTags[];
}
const Hold: React.FC = () => {
  const location = useLocation();
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [hotTourData, setHotTourData] = useState<TourList[]>([]);
  const [hotActData, setHotActData] = useState<ActivityList[]>([]);
  const [activeKey, setActiveKey] = useState<string>('1');
  const [countriesData, setCountriesData] = useState<Options[]>([]);
  const [cityData, setCityData] = useState<Options[]>([]);
  const [advType, setAdvType] = useState<Options[]>([]);
  const [footType, setFootType] = useState<Options[]>([]);
  const [cultureType, setCultureType] = useState<Options[]>([]);
  const [lifeType, setLifeType] = useState<Options[]>([]);
  const [tagsOption, setTagsOption] = useState<OptionTags[]>([]);
  const [tourFormBtnLoading, setTourFormBtnLoading] = useState<boolean>(false);
  const [actFormBtnLoading, setActFormBtnLoading] = useState<boolean>(false);
  const getHotTourData = async () => {
    const { rows }: { rows: TourList[] } = await getTourList({
      pageNum: 1,
      pageSize: 5,
      isHot: 1,
    });
    setHotTourData(rows);
  };
  const getHotActivityData = async () => {
    const { rows }: { rows: ActivityList[] } = await getActivityList({
      pageNum: 1,
      pageSize: 5,
      isHot: 1,
    });
    setHotActData(rows);
  };
  const getCountryData = async () => {
    const { rows }: { rows: CountriesList[] } = await getCountriesList({
      pageNum: 1,
      pageSize: 240, // 全部国家列表
    });
    let arr = rows.map((item) => ({
      label: item.cname,
      value: item.cname,
    }));
    setCountriesData(arr);
  };
  const getTypeData = async (dictType: string) => {
    const { data }: { data: CommonData[] } = await getType({
      dictType,
    });
    let arr = data.map((item) => ({
      label: item.dictValue,
      value: item.dictValue,
    }));
    switch (dictType) {
      case 'adv_tag':
        setAdvType(arr);
        break;
      case 'foot':
        setFootType(arr);
        break;
      case 'culture':
        setCultureType(arr);
        break;
      case 'life':
        setLifeType(arr);
        break;
    }
  };
  useEffect(() => {
    if (location['query'].tab === 'tour') {
      setActiveKey('1');
    } else if (location['query'].tab === 'share') {
      setActiveKey('2');
    }
    getHotTourData();
    getHotActivityData();
    getCountryData();
    getTypeData('adv_tag');
    getTypeData('foot');
    getTypeData('culture');
    getTypeData('life');
  }, []);
  const selectAfter = (
    <Select defaultValue="hour" style={{ width: 80 }}>
      <Select.Option value="hour">小时</Select.Option>
      <Select.Option value="day">天</Select.Option>
      <Select.Option value="week">周</Select.Option>
      <Select.Option value="month">月</Select.Option>
    </Select>
  );
  const onChange = (key: string) => {
    setActiveKey(key);
    if (key === '2') {
      let data: OptionTags[] = [
        {
          label: '冒险',
          value: '冒险',
          children: advType,
        },
        {
          label: '食物',
          value: '食物',
          children: footType,
        },
        {
          label: '文化',
          value: '文化',
          children: cultureType,
        },
        {
          label: '生活',
          value: '生活',
          children: lifeType,
        },
      ];
      setTagsOption(data);
    }
  };
  const onFinishTour = async (values: TourFormExtend) => {
    console.log('Success:', values);
    let peopleStartNum: number = 0;
    let peopleEndNum: number = 0;
    if (values.people) {
      peopleStartNum = values.people[0];
      peopleEndNum = values.people[1];
    }
    let postbody: TourFormExtend = { ...values, peopleStartNum, peopleEndNum };
    console.log(postbody);
    delete postbody.people;

    try {
      setTourFormBtnLoading(true);
      const res: any = await addTour(postbody);
      if (res) {
        form.resetFields();
        history.replace('/success');
      }
    } finally {
      setTourFormBtnLoading(false);
    }
  };
  const onFinishAct = async (values: any) => {
    console.log(values);
    let twoArrSting = values.tags.toString();
    let oneArr = twoArrSting.split(',').filter((name: string) => {
      return name !== '冒险' && name !== '食物' && name !== '文化' && name !== '生活';
    });
    let postbody = { ...values };
    delete postbody.tags;
    try {
      setActFormBtnLoading(true);
      const res: any = await addActivity({
        ...postbody,
        tags: oneArr.toString(),
      });
      if (res) {
        form2.resetFields();
        history.replace({
          pathname: '/success',
          query: {
            form: 'act',
          },
        });
      }
    } finally {
      setActFormBtnLoading(false);
    }
  };
  const onChangeCountry = async (value: string) => {
    console.log(`selected ${value}`);
    if (value === undefined || value === '') {
      setCityData([]);
    }
    const { data }: { data: CitiesList[] } = await getCityByCountry({
      country: value,
    });
    let arr = data.map((item) => ({
      label: item.cname,
      value: item.cname,
    }));
    setCityData(arr);
    form.setFieldsValue({
      city: '',
    });
  };
  const onsuccess = (type: string, fileName: string) => {
    switch (type) {
      case 'bacImg':
        form.setFieldsValue({
          bacImg: fileName,
        });
        break;
      case 'picture':
        form.setFieldsValue({
          picture: fileName,
        });
        break;
      case 'imgUrl':
        form2.setFieldsValue({
          imgUrl: fileName,
        });
    }
  };
  const children1 = (
    <Form
      name="basic"
      form={form}
      onFinish={onFinishTour}
      autoComplete="off"
      labelCol={{ span: 3 }}
      scrollToFirstError
    >
      <Form.Item label="冒险标题" name="title" rules={[{ required: true, message: '请输入标题' }]}>
        <Input placeholder="例如：绿湖和圆湖远足" />
      </Form.Item>
      <Form.Item
        label="冒险国家"
        name="country"
        rules={[{ required: true, message: '请选择国家' }]}
      >
        <Select
          showSearch
          placeholder="请选择国家"
          optionFilterProp="children"
          onChange={onChangeCountry}
          filterOption={(input, option) =>
            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
          }
          options={countriesData}
          allowClear
        />
      </Form.Item>
      <Form.Item
        label="冒险城市"
        name="city"
        rules={[{ required: true, message: '请先选择国家后选择城市' }]}
      >
        <Select
          showSearch
          placeholder="请先选择国家后选择城市"
          optionFilterProp="children"
          allowClear
          filterOption={(input, option) =>
            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
          }
          options={cityData}
        />
      </Form.Item>
      <Form.Item label="冒险类型" name="tags" rules={[{ required: true, message: '请输入标题' }]}>
        <Select
          showSearch
          placeholder="请选择冒险类型"
          optionFilterProp="children"
          filterOption={(input, option) =>
            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
          }
          options={advType}
        />
      </Form.Item>
      <Form.Item
        label="冒险时长"
        name="time"
        rules={[
          { required: true, message: '请输入冒险时长' },
          { type: 'number', min: 1, max: 99 },
        ]}
      >
        <InputNumber addonAfter={selectAfter} style={{ width: '100%' }} />
      </Form.Item>
      <Form.Item
        label="冒险费用"
        name="price"
        rules={[
          { required: true, message: '请输入冒险费用' },
          { type: 'number', min: 0, max: 9999 },
        ]}
      >
        <InputNumber addonAfter="元" style={{ width: '100%' }} />
      </Form.Item>
      <Form.Item
        label="冒险人数"
        name="people"
        rules={[{ required: true, message: '请选择冒险人数' }]}
      >
        <Slider range max={10} min={1} />
      </Form.Item>
      <Form.Item
        label="冒险难度"
        name="difficulty"
        rules={[{ required: true, message: '请选择冒险难度' }]}
      >
        <Radio.Group buttonStyle="solid">
          <Radio.Button value="简单">简单</Radio.Button>
          <Radio.Button value="普通">普通</Radio.Button>
          <Radio.Button value="困难">困难</Radio.Button>
          <Radio.Button value="挑战">挑战</Radio.Button>
        </Radio.Group>
      </Form.Item>
      <Form.Item label="摘要" name="abstracts" rules={[{ required: true, message: '请输入摘要' }]}>
        <Input.TextArea
          placeholder="请输入摘要 例如：踏上两轮冒险之旅，以缓慢的速度探索吴哥的辉煌。您将在温度仍然凉爽时提早离开酒店，然后骑自行车前往吴哥窟。"
          maxLength={800}
          showCount
          style={{ height: 150 }}
        />
      </Form.Item>
      <Form.Item
        label="旅行时间"
        name="advTime"
        rules={[{ required: true, message: '请输入旅行时间' }]}
      >
        <Input.TextArea
          placeholder="请输入旅行时间 例如：春季至秋季，通常是周末"
          maxLength={800}
          showCount
          style={{ height: 150 }}
        />
      </Form.Item>
      <Form.Item label="行程" name="trip" rules={[{ required: true, message: '请输入行程' }]}>
        <Input.TextArea
          placeholder="请输入行程 例如：第一天 我们将在绿湖州立公园高尔夫球场的停车场集合，然后前往付费入口后步行道开始的停车场"
          maxLength={800}
          showCount
          style={{ height: 150 }}
        />
      </Form.Item>
      <Form.Item
        label="集合地点"
        name="place"
        rules={[{ required: true, message: '请输入集合地点' }]}
      >
        <Input.TextArea
          placeholder="请输入集合地点 例如：在绿湖州立公园高尔夫球场停车场的5号公路旁"
          maxLength={800}
          showCount
          style={{ height: 150 }}
        />
      </Form.Item>
      <Form.Item label="备注" name="remark">
        <Input.TextArea
          placeholder="请输入备注 例如：
          •出发时间：清晨
          •返回：下午
          •备注：在平坦的地形和铺砌的道路上骑自行车27公里，需要中等水平的健身，提供自行车和头盔
          •您将参观的景点：吴哥窟，巴戎，大象露台，麻风国王露台，塔普伦，斯拉斯朗
          •亮点：积极探索，自然，建筑，历史"
          maxLength={800}
          showCount
          style={{ height: 150 }}
        />
      </Form.Item>
      <Form.Item label="封面图" name="bacImg">
        <PicUpload
          multiple={false}
          maxCount={1}
          onsuccess={(fileName) => {
            onsuccess('bacImg', fileName);
          }}
        ></PicUpload>
      </Form.Item>
      <Form.Item label="旅途照片" name="picture">
        <PicUpload
          multiple={true}
          maxCount={20}
          onsuccess={(fileName) => {
            onsuccess('picture', fileName);
          }}
        ></PicUpload>
      </Form.Item>
      <Form.Item style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Space>
          <Button
            onClick={() => {
              history.push('/');
            }}
          >
            返回首页
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            style={{ width: 300 }}
            loading={tourFormBtnLoading}
          >
            发布
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
  const children2 = (
    <Form
      name="basic"
      onFinish={onFinishAct}
      autoComplete="off"
      form={form2}
      labelCol={{ span: 3 }}
    >
      <Form.Item
        label="活动标题"
        name="title"
        rules={[{ required: true, message: '请输入活动标题' }]}
      >
        <Input placeholder="请输入活动标题 例如: 尼特米鲁克国家公园" />
      </Form.Item>
      <Form.Item label="简介" name="intro" rules={[{ required: true, message: '请输入简介' }]}>
        <Input.TextArea
          maxLength={800}
          showCount
          style={{ height: 150 }}
          placeholder="请输入简介 例如:北领地的顶端是尼特米鲁克国家公园，该地区拥有多样的自然美景，对原住民贾沃恩人具有重要的精神意义。游览通常穿过公园的中心，凯瑟琳峡谷，该峡谷由13个峡谷组成，是蜿蜒的峡谷，瀑布和偶尔的鳄鱼（相当无害）的所在地。对于勇敢的旅行者来说，也有很多人行道，尽管最史诗般的是贾特布拉小径，通常包括前往壮观的伊迪丝瀑布的 5 天徒步旅行。"
        />
      </Form.Item>
      <Form.Item label="国家" name="country" rules={[{ required: true, message: '请选择国家' }]}>
        <Select
          showSearch
          placeholder="请选择国家"
          optionFilterProp="children"
          onChange={onChangeCountry}
          filterOption={(input, option) =>
            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
          }
          options={countriesData}
          allowClear
        />
      </Form.Item>
      <Form.Item
        label="城市"
        name="city"
        rules={[{ required: true, message: '请先选择国家后选择城市' }]}
      >
        <Select
          showSearch
          placeholder="请先选择国家后选择城市"
          optionFilterProp="children"
          allowClear
          filterOption={(input, option) =>
            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
          }
          options={cityData}
        />
      </Form.Item>
      <Form.Item label="标签" name="tags" rules={[{ required: true, message: '请选择标签' }]}>
        <Cascader
          style={{ width: '100%' }}
          multiple
          options={tagsOption}
          maxTagCount="responsive"
          placeholder="请选择活动标签"
          showCheckedStrategy={SHOW_CHILD}
        />
      </Form.Item>
      <Form.Item label="备注" name="describes">
        <Input placeholder="请输入备注" />
      </Form.Item>
      <Form.Item label="图片上传" name="imgUrl">
        <PicUpload
          maxCount={1}
          multiple={false}
          onsuccess={(fileName) => {
            onsuccess('imgUrl', fileName);
          }}
        ></PicUpload>
      </Form.Item>
      <Form.Item style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Space>
          <Button
            onClick={() => {
              history.push('/');
            }}
          >
            返回首页
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            style={{ width: 300 }}
            loading={actFormBtnLoading}
          >
            发布
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
  return (
    <Layouts>
      <div className="hold_container">
        <div className="h_left">
          <Tabs
            defaultActiveKey="1"
            activeKey={activeKey}
            onChange={onChange}
            items={[
              {
                label: `举办探险`,
                key: '1',
                children: children1,
              },
              {
                label: `分享活动`,
                key: '2',
                children: children2,
              },
            ]}
          />
        </div>
        <div className="h_right">
          <Card title="热门冒险" size="small" style={{ margin: '20px 0' }}>
            {hotTourData.length !== 0 &&
              hotTourData.map((item) => (
                <div
                  className="tour_item"
                  onClick={() => {
                    history.push('/tours-detail/' + item.id);
                  }}
                >
                  <div className="tour_left">
                    <img
                      src={
                        item.bacImg
                          ? configs[process.env.API_ENV as any].API_SERVER + item.bacImg
                          : '/images/16648898720.jpg'
                      }
                      alt=""
                    />
                  </div>
                  <div className="tour_right">{item.title}</div>
                </div>
              ))}
            {hotTourData.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
          </Card>
          <Card title="热门活动" size="small">
            {hotActData.length !== 0 &&
              hotActData.map((item) => (
                <div className="tour_item">
                  <div className="tour_left">
                    <img
                      src={
                        item.imgUrl
                          ? configs[process.env.API_ENV as any].API_SERVER + item.imgUrl
                          : '/images/16643897481.jpeg'
                      }
                      alt=""
                    />
                  </div>
                  <div className="tour_right">{item.title}</div>
                </div>
              ))}
            {hotActData.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
          </Card>
        </div>
      </div>
    </Layouts>
  );
};

export default Hold;
